package com.xx.job.controller;

import com.xx.job.common.CommonResult;
import com.xx.job.entity.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    // 有了LoadBalanced注解，我们可以不用写ip地址，直接写应用的名称。
    // 比如我们有两个一样的服务只是端口号不同，那就可以通服务名去调用服务。
    public static final String URI = "http://SPRING-CLOUD-PAYMENT";

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/selectById/{id}")
    public CommonResult selectById(@PathVariable Long id){
        ResponseEntity<CommonResult> forEntity = restTemplate.getForEntity(URI + "/payment/selectById/" + id, CommonResult.class);
        CommonResult body = forEntity.getBody();
        return body;
    }

    @GetMapping("/insert")
    public CommonResult insert( Payment payment){
        ResponseEntity<CommonResult> forEntity = restTemplate.postForEntity(URI + "/payment/insert", payment, CommonResult.class);
        return forEntity.getBody();
    }

    @GetMapping("/discovery")
    public Object discoveryClient(){
        List<String> services = discoveryClient.getServices();
        services.forEach(x->{
            System.out.println(x);
        });

        List<ServiceInstance> instances = discoveryClient.getInstances("SPRING-CLOUD-PAYMENT");
        instances.forEach(x->{
            System.out.println(x.getHost());
            System.out.println(x.getInstanceId());
            System.out.println(x.getPort());
            System.out.println(x.getServiceId());
            System.out.println(x.getUri());
            System.out.println(x.getMetadata());
            System.out.println(x.getScheme());
            System.out.println("------------------------");
        });

        return discoveryClient;
    }
}
